# -*- coding: utf-8 -*-

from __future__ import unicode_literals, print_function

import logging
import sys, os
import copy

import smvn.template as tpl
import smvn.config as cfg
from smvn.util import get_file_type, pjoin
from smvn.core import Artifact, Repo, XmlPom, get_all_info, get_xml, update_pom_from_kb_input

dr=Repo()

def help_handler(fmap, args):
    print(
"""
    arche:check  <pom.xml>          check arche
    arche:create [pom.xml]          create a source directory layout
    arche:mkcm   [pom.xml]          make a CMakeLists.txt file by guess
    arche:mkpom                     make a pom.xml for trying
    arche:tos                       turn all filenames to short format
    arche:tol                       turn all filenames to long format\
"""
    )

def ver_handler(fmap, args):
    print("0.0.1")

def check_handler(fmap, args):
    """
     check whether naming of the files is OK
    """
    p, r = get_all_info(fmap, get_xml(args))
    pass

def binfo_handler(fmap, args):
    bdir = 'bdef'
    if (os.path.exists(cfg.default_buildinfo_name)):
        with open(cfg.default_buildinfo_name) as bi:
            print('Current build info:', bi.read().strip())
    if (len(args) > 1):
        bdir = args[1]
        os.remove(cfg.default_buildinfo_name)
    if not os.path.exists(bdir):
        os.makedirs(bdir)
    os.chdir(bdir)
    os.system('cmake ..')

def create_handler(fmap, args):
    """
     create dir structure of a pom
    """
    #p, r = get_all_info(fmap, get_xml(args))
    p, r = update_pom_from_kb_input(args[1:])
    #dirname = p.artifactId
    if os.path.exists(p.get_src_prefix()):
        logging.warn("Not a clean dir, do not create any dirs")
    else:
        p.create_comp_skeleton()

    if not os.path.exists('pom.xml'):
        logging.info('>>> Making pom')
        p.write_xml('pom.xml')

    if not os.path.exists('CMakeLists.txt'):
        logging.info('>>> Making cmakelists.txt')
        p.write_cmake(tpl.cmake_root_template%(p.keymap))

    if not os.path.exists(cfg.default_buildinfo_name):
        logging.info('>>> Making buildinfo')
        p.write_file(cfg.default_lib_path, cfg.default_buildinfo_name)

def mkcm_handler(fmap, args):
    pass

def mkpom_handler(fmap, args):
    if (len(args) > 1):
        dirpath = args[1]
    else:
        dirpath = '.'

    p = XmlPom(pjoin(dirpath, "pom.xml"))
    np = copy.copy(p)
    np.reset_items()

    pathlist = os.path.abspath(dirpath).split(os.sep)
    name = pathlist[-2]
    ver = pathlist[-1]

    print(name, ver, Artifact.get_file_version('-'+ver), np.artifactId)
    if (Artifact.get_file_version('-'+ver) is not None):
        np.version = ver
        if np.artifactId == '':
            # default Id
            np.artifactId = name
            try:
                si = pathlist.index(cfg.default_home_dir)
                groupl = pathlist[si+1:-2]
                groupstr = ""
                for g in groupl:
                    groupstr += g
                    groupstr += '.'
                np.groupId = groupstr[0:-1]
                #print("Group", groupl)
            except ValueError, e:
                # not in list
                pass

    ret = os.walk(dirpath)
    for root, dirs, files in ret:
        if root == dirpath:
            # 遍历根目录的文件
            for sfile in files:
                fm, fe = os.path.splitext(sfile)
                if get_file_type(fe) == '.lib':
                    np.add_lib(sfile)
                elif get_file_type(fe) == '.xml':
                    pass
                elif get_file_type(fe) == '.h':
                    np.add_header(sfile)
                else:
                    pass
        elif root != default_home_dir:
            nroot = os.path.relpath(root, dirpath).replace('\\', '/')
            np.add_headerdir(nroot)
            for sfile in files:
                np.add_headerdir(nroot, sfile)

    nstr = np.xml()
    print(nstr)
    if (fmap.flag_get('write')):
        with open('pom.xml', 'w') as f:
            f.write(nstr)
            f.close

def tos_handler(fmap, args):
    if (len(args) > 1):
        dirpath = args[1]
    else:
        dirpath = '.'

    p = XmlPom(pjoin(dirpath, "pom.xml"))
    a = Artifact(p.groupId, p.artifactId, p.version)
    dr.rename_dir2short(dirpath, a)

def tol_handler(fmap, args):
    if (len(args) > 1):
        dirpath = args[1]
    else:
        dirpath = '.'
    p = XmlPom(pjoin(dirpath, "pom.xml"))
    #print(dirpath, p.groupId, p.version)
    a = Artifact(p.groupId, p.artifactId, p.version)
    dr.rename_dir2long(dirpath, a)
